﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NExplorer.AddIns.Samples
{
	internal class FolderSizeColumnProvider : IColumnProvider
	{
		private IExplorerService _explorerService;

		public FolderSizeColumnProvider()
		{
			_explorerService = ServiceManager.Explorer;	
		}

		public string ColumnHeader
		{
			get { return "Folder Size"; }
		}

		public IComparer ItemComparer
		{
			get { return Comparer.DefaultInvariant; }
		}

		public int DefaultWidth
		{
			get { return 130; }
		}

		public HorizontalAlignment Alignment
		{
			get { return HorizontalAlignment.Right; }
		}

		public void ProcessItem(Guid directoryId, int columnId, FileSystemInfo item)
		{
			DirectoryInfo dirInfo = item as DirectoryInfo;

			if (dirInfo != null)
			{
				string text;
				long size;

				try
				{
					FileInfo[] files = dirInfo.GetFiles();
					size = files.Sum(file => file.Length);
					text = string.Format("{0:n0} B", size);
				}
				catch (UnauthorizedAccessException)
				{
					// Not much we can do about this.
					text = " - ";
					size = 0;
				}

				_explorerService.UpdateColumnItem(directoryId, columnId, item, new ColumnItemData(text, size));
			}
		}
	}
}
